package com.neuedu.service.impl;

import com.aventrix.jnanoid.jnanoid.NanoIdUtils;
import com.neuedu.entity.Wyfile;
import com.neuedu.service.FileUploadService;
import com.neuedu.service.WyfileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Value("${minio.url}")
    String url;
    @Value("${minio.username}")
    String username;
    @Value("${minio.password}")
    String password;
    @Resource
    WyfileService wyfileService;
    @Override
    public String upload(MultipartFile file, String bucket) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException, InterruptedException {
        // 先拿到文件的md5 大小 类型
        long size = file.getSize();
        String type = file.getContentType(); // 文件类型
        String md5 = DigestUtils.md5Hex(file.getInputStream()); // 文件md5
        Wyfile wyfile = wyfileService.get(md5, size, type);
        if (null != wyfile) { // 文件已存在
            return wyfile.getPath();
        }
        // 生成文件名
        String rename = String.format("%s.%s", NanoIdUtils.randomNanoId(), FilenameUtils.getExtension(file.getOriginalFilename()));
        MinioClient client = MinioClient.builder()  // 创建客户端
                .endpoint(url) // 地址
                .credentials(username, password) // 用户名 密码
                .build();
        PutObjectArgs args = PutObjectArgs // 创建上传参数
                .builder()
                .object(rename) // 文件名
                .bucket(bucket)  // 桶名
                .contentType(type) // 文件类型
                .stream(file.getInputStream(), size, 0) // 文件流 大小
                .build();
        client.putObject(args); // 上传
        String path = String.format("/%s/%s", bucket, rename); // 文件路径
        wyfile = new Wyfile(null, md5, size, type, path);
        wyfileService.save(wyfile);
        return path;
    }
}
